﻿using AntdUI;
using PosClient.Controls;
using PosClient.Event;
using ReactiveUI;
using ReactiveUI.Fody.Helpers;
using Splat;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Windows.Forms;
using DynamicData;
using PosClient.ViewModel;
using System.Linq;
using System.Diagnostics;
using PosClient.Model;

namespace PosClient.View
{
    public partial class PayView : Window, IViewFor<PayViewModel>
    {
        object IViewFor.ViewModel
        {
            get => ViewModel;
            set => ViewModel = (PayViewModel)value;
        }
        public PayViewModel ViewModel { get; set; }
        public PayView()
        {
            InitializeComponent();
            InitListen();
            InitBinding();
            InitLoad();
            InitEvent();
        }

        private void InitBinding()
        {
            var parentViewModel = Locator.Current.GetService<MainViewModel>();
            ViewModel.TotalAmount = parentViewModel.TotalAmount;
            ViewModel.TotalCount = parentViewModel.TotalCount;
            ViewModel.TotalDiscount = parentViewModel.TotalDisAmount;
            this.WhenActivated(d =>
            {
                this.Events().Load
                    .Do(x => 
                    { 
                        ActiveControl = input_input; 
                        input_input.SelectAll(); 
                    }).Subscribe()
                    .DisposeWith(d);

                this.Bind(ViewModel,
                    vm => vm.PayList,
                    v => v.payGrid.DataSource
                    ).DisposeWith(d);

                this.Bind(ViewModel,
                    vm => vm.PayAmountString,
                    v => v.input_input.Text
                    ).DisposeWith(d);

                this.OneWayBind(ViewModel,
                    vm => vm.PayTitle,
                    v => v.label_total.Text
                    ).DisposeWith(d);

                this.OneWayBind(ViewModel,
                    vm => vm.PaySubTitle,
                    v => v.label_paid.Text
                    ).DisposeWith(d);

                this.Events()
                    .KeyPress
                    .Do(e =>
                {
                    int key = Convert.ToInt32(e.KeyChar);
                    // 数字、backspace、dot
                    if (!(48 <= key && key <= 58 || key == 8 || key == 46))
                    {
                        e.Handled = true;
                    }
                })
                    .Subscribe()
                    .DisposeWith(d);

                this.Events()
                    .Closing
                    .Do(x =>
                {
                    ViewModel.ResetCommand.Execute().Subscribe();
                    this.Dispose();
                })
                    .Subscribe()
                    .DisposeWith(d);

            });

        }

        private void InitLoad()
        {
            Globals.PayForm = this;
            ViewModel.CacheExchangeGoodCommand.Execute().Subscribe();
        }

        private void InitListen()
        {
            ViewModel = Locator.Current.GetService<PayViewModel>();
            //添加支付后处理
            MessageBus.Current.Listen<AddPayEventArgs>()
                .ObserveOn(RxApp.MainThreadScheduler)
                .Subscribe(e =>
                {
                    Console.WriteLine(e.Pays.Count > 0 ? e.Pays.FirstOrDefault().PayName : "触发");
                    CreateTag(e);
                });
            
            //结账成功处理
            MessageBus.Current.Listen<SettlePayEventArgs>()
                .Subscribe(e =>
                {
                    var result = e.Result;
                    if (result.Success)
                    {

                        pageHeader_title.SubText += "（退出键退出）";
                        label_total.Text += $",找零{ViewModel.ExchangeAmount}元";
                        if (MessageBox.Show("是否打印小票？", "提醒", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                        {
                            //这里放打印逻辑
                        }
                        if (ViewModel.ExchangeAmount == 0)
                        {
                            Close();
                        }
                    }
                    else
                    {
                        var config = new Notification.Config(Globals.MainForm, "结账", result.Message, TType.Error, TAlignFrom.Top);
                        Notification.open(config);
                        ActiveControl = input_input;
                        input_input.Focus();
                        input_input.Select();
                    }
                });
        }

        private void InitEvent()
        {
            this.Load += (s, e) =>
            {
                this.Activate();

                var btnList = new List<FloatButton.ConfigBtn>();
                var btn1 = new FloatButton.ConfigBtn("FloatButton1")
                {
                    Text = "打开换购[E]",
                    Type = TTypeMini.Primary
                };
                btnList.Add(btn1);
                var config = new FloatButton.Config(this, btnList.ToArray(), btn =>
                {
                    Console.WriteLine(btn.Name);
                    ViewModel.OpenExchangeGoodCommand.Execute().Subscribe();
                });
                config.Align = TAlign.RB;
                config.Size = 65;
                FloatButton.open(config);
            };

            this.KeyDown += (s, e) =>
            {
                payGrid.GridKeyDown(e.KeyData);
                if (e.KeyData == Keys.Escape)
                {
                    Close();
                }
            };

            this.KeyUp += (s, e) =>
            {
                payGrid.GridKeyUp(e.KeyData);
            };

            this.payGrid.GridIndex += (s, e) =>
            {
                var activeControl = (s as PayRow);
                ActiveControl = input_input;
                input_input.SelectAll();
                ViewModel.Index = activeControl.Index;
                ViewModel.IndexChangeCommand.Execute().Subscribe();
                string msg = "";
                if (ViewModel.SelectPay.IsRefund == 0)
                {
                    msg = "使用该支付方式默认不允许退货";
                }
                if (ViewModel.SelectPay.IsVip == 0)
                {
                    msg = "使用该支付方式默认取消会员优惠";
                }
                if (ViewModel.SelectPay.IsRound == 1)
                {
                    msg = "使用该支付方式默认抹零";
                }
                if (msg.Length > 0)
                {
                    var config = new Tooltip.Config(activeControl, msg);
                    config.ArrowAlign = TAlign.Top;
                    
                    Tooltip.open(config);
                }
            };

            this.payGrid.ConfirmPay += (s, e) =>
            {
                ViewModel.ConfirmCommand.Execute().Subscribe(result =>
                {
                    if (result.Success && result.Data != null)
                    {
                        ScanPayView view = new ScanPayView(ViewModel);
                        view.Show();
                    }
                    else
                    {
                        ActiveControl = input_input;
                        input_input.SelectAll();
                    }
                });
            };
        }

        private void CreateTag(AddPayEventArgs e)
        {
            flowPanel_pay.Controls.Clear();
            foreach (var orderPay in e.Pays)
            {
                string value = orderPay.PayName + " " + orderPay.PayAmount + " " + "元";
                if (!string.IsNullOrEmpty(value))
                {
                    AntdUI.Tag tag = new AntdUI.Tag();
                    tag.CloseIcon = false;
                    tag.Text = value;
                    tag.AutoSize = true;
                    switch (orderPay.PayType)
                    {
                        case 0:
                            tag.Type = TTypeMini.Warn;
                            break;
                        case 1:
                            tag.Type = TTypeMini.Success;
                            break;
                        case 2:
                            tag.Type = TTypeMini.Error;
                            break;
                        case 4:
                            tag.Type = TTypeMini.Default;
                            break;
                        case 5:
                            tag.Type = TTypeMini.Warn;
                            break;
                        case 6:
                            tag.Type = TTypeMini.Success;
                            break;
                        case 7:
                            tag.Type = TTypeMini.Primary;
                            break;
                        default:
                            tag.Type = TTypeMini.Primary;
                            break;
                    }
                    flowPanel_pay.Controls.Add(tag);
                }
            }
        }
    }
}
